package com.jhgsys.internal.common.authentication;

import com.jhgsys.internal.common.utils.SpringContextUtil;
import com.jhgsys.internal.monitor.service.IEhcacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtFilter extends OncePerRequestFilter {

    /**
     * request请求头属性
     */
    public static final String REQUEST_AUTH_HEADER="Authorization";

    private int timeout = 30*60;//默认为30分钟过期

    public JwtFilter(int timeout) {
        if (timeout > 0) {
            this.timeout = timeout;
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        if (!httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())
                && httpRequest.getRequestURI().contains("webmember")) {
            String authorization = httpRequest.getHeader(REQUEST_AUTH_HEADER);
            if (authorization == null) {
                //必须包含token头
                log.error("非法请求！");
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            IEhcacheService jedisUtils = SpringContextUtil.getBean(IEhcacheService.class);
            //判断Key是否存在
            if (jedisUtils.hasKey(authorization)) {
                jedisUtils.expire(authorization, timeout);
                BaseThreadDataStorage.put(BaseThreadDataStorage.TOKEN_KEY, authorization);
            } else {
                //过期了
                log.error("登录过期，请重新登录！");
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        BaseThreadDataStorage.remove(BaseThreadDataStorage.TOKEN_KEY);
        super.destroy();
    }
}
